import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, Select, Radio, Space, Tabs, message, InputNumber } from 'antd';
import {
  FolderOutlined,
  TagOutlined,
  KeyOutlined,
  LockOutlined,
  UserOutlined,
  GlobalOutlined,
} from '@ant-design/icons';
import {
  ConnectionInfo,
  ConnectionAuth,
  AuthType,
  PortForwardRule,
  PortForwardType,
} from '@shared/types';
import { useConnectionsStore } from '@renderer/stores/connectionsStore';
import { v4 as uuidv4 } from 'uuid';

interface ConnectionEditModalProps {
  visible: boolean;
  onClose: () => void;
  connectionId?: string;
}

const { TabPane } = Tabs;
const { Option } = Select;

export const ConnectionEditModal: React.FC<ConnectionEditModalProps> = ({
  visible,
  onClose,
  connectionId,
}) => {
  const [form] = Form.useForm();
  const { connections, groups, connectionAuths, addConnection, updateConnection, addConnectionAuth, updateConnectionAuth } = useConnectionsStore();
  const [activeTab, setActiveTab] = useState('basic');
  const [portForwards, setPortForwards] = useState<PortForwardRule[]>([]);
  const [editingForwardId, setEditingForwardId] = useState<string | null>(null);
  const [newForward, setNewForward] = useState({
    type: 'local' as PortForwardType,
    localPort: '',
    remoteHost: '',
    remotePort: '',
  });

  // 编辑模式
  const isEditMode = Boolean(connectionId);
  const editingConnection = connectionId ? connections.find(conn => conn.id === connectionId) : undefined;
  const editingAuth = connectionId ? connectionAuths.find(auth => auth.connectionId === connectionId) : undefined;

  // 初始化表单数据
  useEffect(() => {
    if (visible) {
      if (isEditMode && editingConnection) {
        // 编辑模式 - 填充表单
        form.setFieldsValue({
          name: editingConnection.name,
          host: editingConnection.host,
          port: editingConnection.port,
          username: editingConnection.username || editingAuth?.username,
          authType: editingConnection.authType || 'password',
          groupId: editingConnection.groupId,
          tags: editingConnection.tags?.join(', ') || '',
          description: editingConnection.description,
          timeout: editingConnection.timeout || 30,
          keepAlive: editingConnection.keepAlive !== false,
          keepAliveInterval: editingConnection.keepAliveInterval || 60,
          reconnectTries: editingConnection.reconnectTries || 3,
        });

        // 填充认证信息
        if (editingAuth) {
          form.setFieldsValue({
            authType: editingAuth.authType,
          });
        }

        // 填充端口转发规则
        setPortForwards(editingConnection.portForwards || []);
      } else {
        // 新建模式 - 重置表单
        form.resetFields();
        form.setFieldsValue({
          port: 22,
          authType: 'password',
          timeout: 30,
          keepAlive: true,
          keepAliveInterval: 60,
          reconnectTries: 3,
        });
        setPortForwards([]);
        setNewForward({
          type: 'local',
          localPort: '',
          remoteHost: '',
          remotePort: '',
        });
      }
      setActiveTab('basic');
    }
  }, [visible, isEditMode, editingConnection, editingAuth]);

  // 处理保存
  const handleSave = async () => {
    try {
      const values = await form.validateFields();

      // 基础数据
      const baseData = {
        name: values.name.trim(),
        host: values.host.trim(),
        port: values.port,
        username: values.username.trim(),
        authType: values.authType,
        groupId: values.groupId,
        tags: values.tags ? values.tags.split(',').map((tag: string) => tag.trim()).filter(Boolean) : [],
        description: values.description?.trim(),
        timeout: values.timeout,
        keepAlive: values.keepAlive,
        keepAliveInterval: values.keepAliveInterval,
        reconnectTries: values.reconnectTries,
        portForwards: portForwards,
      };

      if (isEditMode && connectionId) {
        // 更新连接
        await updateConnection(connectionId, baseData);

        // 更新认证信息
        if (editingAuth) {
          const authUpdates: Partial<ConnectionAuth> = {
            authType: values.authType,
            username: values.username,
          };

          if (values.password && values.authType === 'password') {
            authUpdates.password = values.password;
          }

          if (values.privateKey && values.authType === 'key') {
            authUpdates.privateKey = values.privateKey;
            authUpdates.keyPassword = values.keyPassword;
          }

          await updateConnectionAuth(connectionId, authUpdates);
        }

        message.success('连接已更新');
      } else {
        // 新建连接
        const connectionId = await addConnection(baseData as any);

        // 保存认证信息
        const authData: Omit<ConnectionAuth, 'id' | 'updatedAt'> = {
          connectionId,
          authType: values.authType,
          username: values.username,
        };

        if (values.password && values.authType === 'password') {
          authData.password = values.password;
        }

        if (values.privateKey && values.authType === 'key') {
          authData.privateKey = values.privateKey;
          authData.keyPassword = values.keyPassword;
        }

        await addConnectionAuth(authData);

        message.success('连接已创建');
      }

      onClose();
    } catch (error) {
      console.error('保存失败:', error);
    }
  };

  // 处理添加端口转发规则
  const handleAddPortForward = () => {
    if (!newForward.localPort || !newForward.remoteHost || !newForward.remotePort) {
      message.error('请填写完整的端口转发信息');
      return;
    }

    const rule: PortForwardRule = {
      id: uuidv4(),
      type: newForward.type,
      localPort: parseInt(newForward.localPort),
      remoteHost: newForward.remoteHost,
      remotePort: parseInt(newForward.remotePort),
      enabled: true,
    };

    setPortForwards([...portForwards, rule]);
    setNewForward({
      type: 'local',
      localPort: '',
      remoteHost: '',
      remotePort: '',
    });
  };

  // 处理删除端口转发规则
  const handleDeletePortForward = (id: string) => {
    setPortForwards(portForwards.filter(rule => rule.id !== id));
  };

  // 处理编辑端口转发规则
  const handleEditPortForward = (id: string) => {
    const rule = portForwards.find(r => r.id === id);
    if (rule) {
      setEditingForwardId(id);
      setNewForward({
        type: rule.type,
        localPort: rule.localPort.toString(),
        remoteHost: rule.remoteHost,
        remotePort: rule.remotePort.toString(),
      });
    }
  };

  // 处理保存编辑的端口转发规则
  const handleSaveEditedPortForward = () => {
    if (!editingForwardId || !newForward.localPort || !newForward.remoteHost || !newForward.remotePort) {
      message.error('请填写完整的端口转发信息');
      return;
    }

    setPortForwards(portForwards.map(rule =>
      rule.id === editingForwardId
        ? {
            ...rule,
            type: newForward.type,
            localPort: parseInt(newForward.localPort),
            remoteHost: newForward.remoteHost,
            remotePort: parseInt(newForward.remotePort),
          }
        : rule
    ));

    setEditingForwardId(null);
    setNewForward({
      type: 'local',
      localPort: '',
      remoteHost: '',
      remotePort: '',
    });
  };

  const modalTitle = isEditMode ? '编辑连接' : '新建连接';

  return (
    <Modal
      title={modalTitle}
      visible={visible}
      onOk={handleSave}
      onCancel={onClose}
      width={680}
      centered
      bodyStyle={{ maxHeight: '70vh', overflow: 'auto', padding: '12px 24px' }}
      okText="保存"
      cancelText="取消"
      styles={{ mask: { backdropFilter: 'blur(2px)' } }}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          port: 22,
          authType: 'password',
          timeout: 30,
          keepAlive: true,
          keepAliveInterval: 60,
          reconnectTries: 3,
        }}
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="基本信息" key="basic">
            <Form.Item
              name="name"
              label="连接名称"
              rules={[
                { required: true, message: '请输入连接名称' },
                { max: 50, message: '名称最多50个字符' },
              ]}
            >
              <Input placeholder="例如: 生产服务器" />
            </Form.Item>

            <Form.Item
              name="host"
              label="主机地址"
              rules={[
                { required: true, message: '请输入主机地址' },
                { pattern: /^(\d{1,3}\.){3}\d{1,3}$|^[a-zA-Z0-9.-]+$/, message: '请输入有效的IP地址或域名' },
              ]}
            >
              <Input placeholder="例如: 192.168.1.100" addonBefore={<GlobalOutlined />} />
            </Form.Item>

            <Form.Item
              name="port"
              label="端口"
              rules={[
                { required: true, message: '请输入端口号' },
                { type: 'number', min: 1, max: 65535, message: '端口范围1-65535' },
              ]}
            >
              <InputNumber min={1} max={65535} style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item
              name="username"
              label="用户名"
              rules={[
                { required: true, message: '请输入用户名' },
                { max: 32, message: '用户名最多32个字符' },
              ]}
            >
              <Input placeholder="例如: root" addonBefore={<UserOutlined />} />
            </Form.Item>

            <Form.Item name="authType" label="认证方式">
              <Radio.Group>
                <Radio value="password">
                  <LockOutlined /> 密码认证
                </Radio>
                <Radio value="key">
                  <KeyOutlined /> 密钥认证
                </Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.authType !== currentValues.authType}>
              {({ getFieldValue }) => {
                const authType = getFieldValue('authType');
                return authType === 'password' ? (
                  <Form.Item
                    name="password"
                    label="密码"
                    rules={[{ required: !isEditMode, message: '请输入密码' }]}
                  >
                    <Input.Password placeholder="输入密码" />
                  </Form.Item>
                ) : (
                  <>
                    <Form.Item
                      name="privateKey"
                      label="私钥文件"
                      rules={[{ required: !isEditMode, message: '请上传私钥文件' }]}
                    >
                      <Input.TextArea rows={10} placeholder="粘贴私钥内容" />
                    </Form.Item>
                    <Form.Item name="keyPassword" label="密钥密码（可选）">
                      <Input.Password placeholder="如果私钥有密码，请输入" />
                    </Form.Item>
                  </>
                );
              }}
            </Form.Item>
          </TabPane>

          <TabPane tab="高级选项" key="advanced">
            <Form.Item name="groupId" label="分组">
              <Select placeholder="选择分组" allowClear>
                {groups
                  .filter((g) => g.id !== 'default')
                  .map((group) => (
                    <Option key={group.id} value={group.id}>
                      {group.name}
                    </Option>
                  ))}
              </Select>
            </Form.Item>

            <Form.Item name="tags" label="标签">
              <Input placeholder="输入标签，用逗号分隔，例如: web, production" />
            </Form.Item>

            <Form.Item name="description" label="描述">
              <Input.TextArea rows={3} placeholder="连接描述（可选）" />
            </Form.Item>

            <Form.Item
              name="timeout"
              label="连接超时（秒）"
              rules={[{ type: 'number', min: 5, max: 300, message: '超时时间范围5-300秒' }]}
            >
              <InputNumber min={5} max={300} style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item name="keepAlive" valuePropName="checked">
              <Radio.Group buttonStyle="solid">
                <Radio value={true}>启用保持连接</Radio>
                <Radio value={false}>禁用保持连接</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.keepAlive !== currentValues.keepAlive}>
              {({ getFieldValue }) => {
                const keepAlive = getFieldValue('keepAlive');
                return keepAlive ? (
                  <>
                    <Form.Item
                      name="keepAliveInterval"
                      label="心跳间隔（秒）"
                      rules={[{ type: 'number', min: 10, message: '心跳间隔至少10秒' }]}
                    >
                      <InputNumber min={10} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item
                      name="reconnectTries"
                      label="重连次数"
                      rules={[{ type: 'number', min: 0, max: 10, message: '重连次数范围0-10' }]}
                    >
                      <InputNumber min={0} max={10} style={{ width: '100%' }} />
                    </Form.Item>
                  </>
                ) : null;
              }}
            </Form.Item>
          </TabPane>

          <TabPane tab="端口转发" key="port-forward">
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Select
                  value={newForward.type}
                  onChange={(value) => setNewForward({ ...newForward, type: value })}
                  style={{ width: 100 }}
                >
                  <Option value="local">本地</Option>
                  <Option value="remote">远程</Option>
                  <Option value="dynamic">动态</Option>
                </Select>
                {newForward.type !== 'dynamic' && (
                  <>
                    <Input
                      placeholder="本地端口"
                      value={newForward.localPort}
                      onChange={(e) => setNewForward({ ...newForward, localPort: e.target.value })}
                      style={{ width: 100 }}
                    />
                    <span style={{ color: '#666' }}>→</span>
                  </>
                )}
                {newForward.type !== 'dynamic' && (
                  <>
                    <Input
                      placeholder="远程主机"
                      value={newForward.remoteHost}
                      onChange={(e) => setNewForward({ ...newForward, remoteHost: e.target.value })}
                      style={{ width: 120 }}
                    />
                    <Input
                      placeholder="远程端口"
                      value={newForward.remotePort}
                      onChange={(e) => setNewForward({ ...newForward, remotePort: e.target.value })}
                      style={{ width: 100 }}
                    />
                  </>
                )}
                {editingForwardId ? (
                  <>
                    <Button type="primary" size="small" onClick={handleSaveEditedPortForward}>
                      保存
                    </Button>
                    <Button size="small" onClick={() => {
                      setEditingForwardId(null);
                      setNewForward({ type: 'local', localPort: '', remoteHost: '', remotePort: '' });
                    }}>
                      取消
                    </Button>
                  </>
                ) : (
                  <Button type="primary" size="small" onClick={handleAddPortForward}>
                    添加
                  </Button>
                )}
              </Space>
            </div>

            {portForwards.length > 0 && (
              <div>
                <h4 style={{ marginBottom: 8 }}>转发规则列表</h4>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {portForwards.map((rule) => (
                    <div
                      key={rule.id}
                      style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        padding: '8px 12px',
                        backgroundColor: '#f5f5f5',
                        borderRadius: 6,
                      }}
                    >
                      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                        <span style={{ color: rule.enabled ? '#52c41a' : '#d9d9d9' }}>
                          {rule.enabled ? '✓' : '○'}
                        </span>
                        <span style={{ fontSize: 12 }}>{rule.type === 'local' ? '本地' : rule.type === 'remote' ? '远程' : '动态'}</span>
                        {rule.type !== 'dynamic' && (
                          <>
                            <span style={{ fontSize: 12 }}>
                              {rule.type === 'local' ? (
                                <>{rule.localPort} → {rule.remoteHost}:{rule.remotePort}</>
                              ) : (
                                <>远程 → {rule.remoteHost}:{rule.remotePort}</>
                              )}
                            </span>
                          </>
                        )}
                      </div>
                      <div>
                        <Button
                          size="small"
                          style={{ marginRight: 8 }}
                          onClick={() => handleEditPortForward(rule.id)}
                        >
                          编辑
                        </Button>
                        <Button size="small" danger onClick={() => handleDeletePortForward(rule.id)}>
                          删除
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </TabPane>
        </Tabs>
      </Form>
    </Modal>
  );
};